import logging
import pickle
from pathlib import Path
import time
import chardet
from typing import List, Tuple, Dict

def setup_logging(log_dir: str = "logs") -> logging.Logger:
    """配置日志系统"""
    log_dir = Path(log_dir)
    log_dir.mkdir(exist_ok=True)
    
    # 清除现有的处理器
    for handler in logging.root.handlers[:]:
        logging.root.removeHandler(handler)
    
    # 创建logger
    logger = logging.getLogger('hmm_system')
    logger.handlers = []
    logger.propagate = False
    logger.setLevel(logging.INFO)
    
    # 创建处理器
    file_handler = logging.FileHandler(
        log_dir / f'system_{time.strftime("%Y%m%d_%H%M%S")}.log'
    )
    console_handler = logging.StreamHandler()
    
    # 创建格式器
    formatter = logging.Formatter(
        '%(asctime)s - %(levelname)s - %(message)s'
    )
    
    # 设置处理器格式
    file_handler.setFormatter(formatter)
    console_handler.setFormatter(formatter)
    
    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)
    
    return logger


def save_model(model, save_path: str, logger: logging.Logger) -> bool:
    """保存模型"""
    try:
        save_dir = Path(save_path).parent
        save_dir.mkdir(parents=True, exist_ok=True)
        
        with open(save_path, 'wb') as f:
            pickle.dump(model, f)
        
        return True
    except Exception as e:
        logger.error(f"模型保存失败: {str(e)}")
        return False

def load_model(model_path: str, logger: logging.Logger):
    """加载模型"""
    try:
        with open(model_path, 'rb') as f:
            return pickle.load(f)
    except Exception as e:
        logger.error(f"模型加载失败: {str(e)}")
        return None

def segment_sentence(sentence: List[str], tags: List[str]) -> List[str]:
    """分词函数"""
    words = []
    current_word = ""

    for char, tag in zip(sentence, tags):
        if tag.startswith('B') or tag.startswith('S'):
            if current_word:
                words.append(current_word)
            current_word = char
        elif tag.startswith('M') or tag.startswith('E'):
            current_word += char
            if tag.startswith('E'):
                words.append(current_word)
                current_word = ""

    if current_word:
        words.append(current_word)

    return words

def calculate_word_index(word_lengths: List[int], position: int) -> int:
    """计算词语索引位置"""
    return sum(word_lengths[:position])

def format_tagged_sentence(words: List[str], tags: List[str]) -> str:
    """格式化标注结果"""
    word_lengths = [len(word) for word in words]
    result = []
    
    for i, word in enumerate(words):
        tag_index = calculate_word_index(word_lengths, i)
        result.append(f"{word}/{tags[tag_index][2:]}")
        
    return "，".join(result)